import React, { useState, useRef, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { FaUser, FaSignInAlt, FaUserPlus, FaChevronDown, FaSpinner } from 'react-icons/fa';
import { useUser } from '../context/UserContext';
import AuthModal from './AuthModal';
import './Header.css';

const Header = ({ navItems }) => {
  const navigate = useNavigate();
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef(null);
  const { user, loading, error, logout } = useUser();

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleLogout = async () => {
    try {
      await logout();
      setIsDropdownOpen(false);
      navigate('/');
    } catch (err) {
      console.error('Logout error:', err);
    }
  };

  const handleAuthClick = () => {
    setIsMenuOpen(false);
    setIsAuthModalOpen(true);
  };

  if (loading) {
    return (
      <header className="header">
        <div className="header-container">
          <div className="loading-spinner">
            <FaSpinner className="spin" />
          </div>
        </div>
      </header>
    );
  }

  return (
    <header className="header">
      <div className="header-container">
        <Link to="/" className="logo">
          <img src="/assets/images/logo.svg" alt="KineticX" />
        </Link>

        <button 
          className="menu-toggle"
          onClick={() => setIsMenuOpen(!isMenuOpen)}
          aria-label="Toggle menu"
          aria-expanded={isMenuOpen}
        >
          <span className="menu-icon"></span>
        </button>

        <nav className={`nav ${isMenuOpen ? 'active' : ''}`}>
          <ul className="nav-list">
            {navItems.map((item, index) => (
              <li key={index} className="nav-item">
                <Link 
                  to={item.path} 
                  className="nav-link"
                  onClick={() => setIsMenuOpen(false)}
                >
                  {item.icon && <span className="nav-icon">{item.icon}</span>}
                  {item.label}
                </Link>
              </li>
            ))}
          </ul>

          {/* 移动端登录入口 */}
          {!user && (
            <div className="mobile-auth">
              <button 
                className="auth-button"
                onClick={handleAuthClick}
              >
                <FaSignInAlt />
                <span>登录/注册</span>
              </button>
            </div>
          )}
        </nav>

        <div className="auth-buttons">
          {user ? (
            <div className="user-menu" ref={dropdownRef}>
              <button 
                className="user-button"
                onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                aria-expanded={isDropdownOpen}
              >
                <img 
                  src={user.avatar || '/assets/images/default-avatar.png'} 
                  alt={user.name} 
                  className="user-avatar"
                  onError={(e) => {
                    e.target.src = '/assets/images/default-avatar.png';
                  }}
                />
                <span className="user-name">{user.name}</span>
                <FaChevronDown className={`dropdown-icon ${isDropdownOpen ? 'open' : ''}`} />
              </button>

              {isDropdownOpen && (
                <div className="dropdown-menu" role="menu">
                  <Link 
                    to="/dashboard" 
                    className="dropdown-item"
                    onClick={() => setIsDropdownOpen(false)}
                    role="menuitem"
                  >
                    控制台
                  </Link>
                  <button 
                    className="dropdown-item"
                    onClick={handleLogout}
                    role="menuitem"
                  >
                    退出登录
                  </button>
                </div>
              )}
            </div>
          ) : (
            <button 
              className="auth-button"
              onClick={handleAuthClick}
            >
              <FaUser />
              <span>登录/注册</span>
            </button>
          )}
        </div>
      </div>

      <AuthModal 
        isOpen={isAuthModalOpen}
        onClose={() => setIsAuthModalOpen(false)}
      />

      {error && (
        <div className="error-banner" role="alert">
          {error}
        </div>
      )}
    </header>
  );
};

export default Header; 